class Person < ActiveRecord::Base
  attr_accessible :landline, :mobile1, :mobile2, :name, :opening_balance, :remarks, :shop_name, :group, :current_balance,:address

  has_many :transactions
  has_many :stocks
  has_many :bills, :foreign_key => 'customer_id'
  has_many :bills, :foreign_key => 'electrician_id'

  validates :mobile1, :numericality => { :only_integer => true, :greater_than => 0, :less_than => 9999999999 }
  validates :mobile2, :numericality => { :only_integer => true, :greater_than => 0, :less_than => 9999999999 }

  accepts_nested_attributes_for :transactions, :allow_destroy => true,:reject_if => lambda { |a| a.valid? }
  before_create :make_current_balance_the_opening_balance

  $person_groups = %w{ customer electrician seller }

  $person_groups.each_with_index do |meth, index|
     define_method("#{meth}?") { group == index }
     define_singleton_method("#{meth}s") { find_all_by_group(index) }
     define_singleton_method("new_#{meth}") { new(:group => index) }
  end

  def update_current_balance_with_transaction(transaction)
    if transaction.is_credit?
      current_balance = current_balance - transaction.amount
    else
      current_balance = current_balance + transaction.amount
    end
    save
  end

  def make_current_balance_the_opening_balance
    current_balance = opening_balance
  end

end
